import { ref, computed } from 'vue';
import { getEventDataHook } from '@/hooks/getEventDataHook.js';
import * as XLSX from 'xlsx';

// 状态变量
export const currentPage = ref(1);
export const pageSize = ref(5);
export const total = ref(0);
export const eventList = ref([]);
export const heatMapFeatures = ref([]);
export const source = ref(null);
export const layer = ref(null);
export const geometry = ref(null);
export const isShow = ref(false);
export const type = ref('eventInfo');

// 计算当前页的数据
export const currentTableData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return eventList.value.slice(startIndex, startIndex + pageSize.value);
});

// 创建图标样式函数
export const createImageStyle = () => {
  return new ol.style.Style({
    image: new ol.style.Icon({
      src: '/images/custom_marker.png',
      scale: 0.5,
      anchor: [0.5, 0.5],
    }),
  });
};

// 添加要素到地图
export const addFeaturesToMap = features => {
  if (source.value) {
    source.value.clear();
  }

  features.forEach(feature => {
    const bound = feature.bound;
    if (bound) {
      const centerCoord = [(bound.xmin + bound.xmax) / 2, (bound.ymin + bound.ymax) / 2];
      const pointFeature = new ol.Feature({
        geometry: new ol.geom.Point(centerCoord),
        properties: feature,
      });
      pointFeature.setStyle(createImageStyle());
      source.value.addFeature(pointFeature);
    }
  });
};

// 处理页码变化
export const handleCurrentChange = val => {
  currentPage.value = val;
  if (geometry.value) {
    queryInfo(geometry.value);
  }
};

// 处理每页显示数量变化
export const handleSizeChange = val => {
  pageSize.value = val;
  currentPage.value = 1;
  if (geometry.value) {
    queryInfo(geometry.value);
  }
};

// 导出Excel功能
export const exportToExcel = () => {
  try {
    const exportData = eventList.value.map(item => ({
      事件编号: item.AttValue[0],
      事件类型: item.AttValue[1],
      事件等级: item.AttValue[2],
      发生时间: item.AttValue[3],
      发生地点: item.AttValue[4],
      车牌号: item.AttValue[5],
      驾驶员: item.AttValue[6],
      处理状态: item.AttValue[7],
    }));

    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '事件列表');

    const colWidths = [{ wch: 15 }, { wch: 12 }, { wch: 12 }, { wch: 20 }, { wch: 20 }, { wch: 12 }, { wch: 10 }, { wch: 10 }];
    worksheet['!cols'] = colWidths;

    XLSX.writeFile(workbook, '事件列表.xlsx');
  } catch (error) {
    console.error('导出Excel失败:', error);
    ElMessage.error('导出失败，请重试');
  }
};

// 初始化绘制工具
export const initDraw = (map, draw, setDraw) => {
  if (!map) {
    console.warn('地图实例未初始化');
    return;
  }

  if (!source.value) {
    source.value = new ol.source.Vector();
    layer.value = new ol.layer.Vector({
      source: source.value,
      zIndex: 999,
    });
    map.addLayer(layer.value);
  }

  if (draw) {
    map.removeInteraction(draw);
  }

  const newDraw = new ol.interaction.Draw({
    source: source.value,
    type: 'LineString',
    geometryFunction: function (coordinates, geometry) {
      if (!geometry) {
        geometry = new ol.geom.Polygon(null);
      }
      var start = coordinates[0];
      var end = coordinates[1];
      geometry.setCoordinates([[start, [start[0], end[1]], end, [end[0], start[1]], start]]);
      return geometry;
    },
    style: new ol.style.Style({
      image: new ol.style.Circle({
        radius: 5,
        fill: new ol.style.Fill({
          color: 'rgba(0, 153, 255)',
        }),
      }),
      stroke: new ol.style.Stroke({
        color: 'rgba(0, 153, 255)',
        width: 2,
      }),
    }),
  });

  newDraw.on('drawend', e => handleDraw(e));
  map.addInteraction(newDraw);
  setDraw(newDraw);
};

// 格式化响应数据
const format = res => {
  res.SFEleArray.forEach(item => {
    if (item.AttValue[7] == 0) {
      item.AttValue[7] = '待处理';
    } else if (item.AttValue[7] == 1) {
      item.AttValue[7] = '已处理';
    } else {
      item.AttValue[7] = '已忽略';
    }
  });
  return res;
};

// 画笔回调
export const handleDraw = e => {
  geometry.value = e.feature.getGeometry();
  queryInfo(geometry.value);
};

// 查询拉框范围的要素信息
export const queryInfo = geometry => {
  let service = {
    name: 'guanggu',
    layerId: 2,
  };
  getEventDataHook({
    size: pageSize.value,
    page: currentPage.value - 1,
    geometry,
    service,
    callback: res => {
      // console.log(444, res);
      const result = format(res);
      // console.log(333, result);
      var formatHeadMap = new Zondy.Format.PolygonJSON();
      heatMapFeatures.value = formatHeadMap.read(result);
      eventList.value = result.SFEleArray;
      total.value = res.TotalCount;
      isShow.value = true;
      addFeaturesToMap(result.SFEleArray);
    },
  });
};

// 类型切换处理
export const handleChange = e => {
  type.value = e;
  isShow.value = true;
};

// 地图点击事件处理
export const handleMapClick = e => {
  if (!e.map) return;

  const pixel = e.pixel;
  const feature = e.map.forEachFeatureAtPixel(pixel, function (feature) {
    return feature;
  });

  if (feature) {
    const properties = feature.get('properties');
    // console.log('点击了要素', properties);
  }
};

// 清理函数
export const cleanup = (map, draw) => {
  if (map) {
    if (draw) {
      map.removeInteraction(draw);
    }
    if (layer.value) {
      map.removeLayer(layer.value);
    }
    map.un('click', handleMapClick);
  }
};
